package sample.util;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ml
 * @create 2017-11-16--10:19
 */
public class Reflectutil {


    public static void setValue(Object target,String fieldName,Object value){
        try {
            Field field=target.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(target,value);
        } catch (Exception e) {
            throw new RuntimeException("反射赋值时出错",e);
        }


    }

    /**
     * 获取对象所有字段的名字
     * @param obj
     * @return
     */
    public static String[] getFieldNames(Object obj){
        Class<?> clazz=obj.getClass();
        Field[] fields=clazz.getDeclaredFields();
        List<String> fieldNames=new ArrayList<>();
        for (Field field : fields) {
            //获取非静态
            if ((field.getModifiers() & Modifier.STATIC) == 0) {
                fieldNames.add(field.getName());
            }
        }
        return fieldNames.toArray(new String[fieldNames.size()]);
    }
}
